<script lang="ts" setup>
import debounce from "@/utils/debounce";
import Lnkyeah from "@/utils/lnkyeah";
import PlayVoice from "@/utils/playVoice";
import { onHide } from "@dcloudio/uni-app";
import { ref } from "vue";

interface ChatItemProps {
  messageId?: string;
  playing?: number;
  voiceTime?: number;
  voiceUrl?: string;
  bgColor?: string;
  color?: string;
}
const props = withDefaults(defineProps<ChatItemProps>(), {
  color: "#333333"
});

const emit = defineEmits(["play"]);
const status = ref<"playing" | "stop">("stop");

const stop = () => {
  Lnkyeah.instance.off("playing");
  PlayVoice.instance.stop();
  status.value = "stop";
};
const playing = async () => {
  status.value = "playing";
  Lnkyeah.instance.emit("playing", props.messageId);
  Lnkyeah.instance.on("playing", async (messageId: string) => {
    Lnkyeah.instance.off("playing");
    status.value = "stop";
  });
  await PlayVoice.instance.play(props.voiceUrl!);
  stop();
};
const onPaused = debounce(async () => {
  if (props.voiceUrl) {
    if (PlayVoice.context.paused) {
      playing();
    } else {
      console.log(PlayVoice.context.src !== props.voiceUrl);
      if (PlayVoice.context.src !== props.voiceUrl) {
        playing();
      } else {
        stop();
      }
    }
  } else {
    uni.showToast({
      title: "播放失败，无音频",
      icon: "none"
    });
  }
});
onHide(stop);
</script>
<template>
  <view class="bubble robot-bubble">
    <view class="content">
      <view class="text" :style="{ background: bgColor }" @click="onPaused">
        <image
          :src="
            status === 'stop'
              ? 'https://wealth-1311286543.cos.ap-guangzhou.myqcloud.com/taoshe/static/icon_stop.png'
              : 'https://wealth-1311286543.cos.ap-guangzhou.myqcloud.com/taoshe/static/icon_playing.png'
          "
          class="icon-audio"
        />
        3s
      </view>
    </view>
  </view>
</template>
<style lang="scss" scoped>
.icon-audio {
  width: 40rpx;
  height: 40rpx;
  margin-right: 16rpx;
}
.bubble {
  position: relative;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 40rpx;
  .content {
    color: #17181c;
    font-size: 14px;
    box-sizing: border-box;
    word-wrap: break-word;
    max-width: 100%;
    text-align: justify;
    position: relative;
  }

  .text {
    padding: 16px;
    border-radius: 10px;
    border-top-left-radius: 0;
    background-color: var(--bg-robot-bubble);
    display: flex;
    align-items: center;
  }
}
</style>
